package cn.koala.key.stock.service.impl;

import cn.koala.key.api.KeyManagementApi;
import cn.koala.key.common.feign.FeignUtils;
import cn.koala.key.common.utils.OrderNoGenerator;
import cn.koala.key.entity.EnterStock;
import cn.koala.key.entity.enums.OrderTypeEnum;
import cn.koala.key.entity.enums.StockInOutEnum;
import cn.koala.key.stock.domain.dto.EnterStockDTO;
import cn.koala.key.stock.domain.dto.StockSearch;
import cn.koala.key.stock.service.EnterStockService;
import cn.seed.common.core.*;
import org.springframework.stereotype.Service;

/**
 * 入库逻辑实现
 * @description
 * @author shuai.xu
 * @time 2019/4/28 16:12
*/
@Service
public class EnterStockServiceImpl implements EnterStockService {

    @Override
    public Result<ResultList<EnterStock>> list(StockSearch enterStockSearch) {
        return FeignUtils.getHttpApi(KeyManagementApi.class).list(enterStockSearch);
    }

    @Override
    public Result insertOrUpdate(EnterStockDTO enterStockDTO) {
        String orderNo = null;
        if (enterStockDTO.getEnterStock().getId() == null){
            //生成入库单
            orderNo = OrderNoGenerator.generateOrderNo(0000,OrderNoGenerator.ORDER_TYPE_STOCK);
            enterStockDTO.getEnterStock().setOrderNo(orderNo);
        }else {
            orderNo = enterStockDTO.getEnterStock().getOrderNo();
        }
        //获取钥匙数量
        enterStockDTO.getEnterStock().setKeyCount(enterStockDTO.getEnterStockDetailList().size());
        //初始化入库单明细
        String finalOrderNo = orderNo;
        enterStockDTO.getEnterStockDetailList().stream().forEach(enterStockDetail -> {
            enterStockDetail.setOrderNo(finalOrderNo);
            enterStockDetail.setIsDeleted(OrderTypeEnum.KEY_NO_DELETE.getValue());
            enterStockDetail.setIsStorage(OrderTypeEnum.KEY_IN_STORE.getValue());
        });
        /**
         * 新车入库没有借用单号
         */
        if (StockInOutEnum.IN_NEW.getValue().equals(enterStockDTO.getEnterStock().getOrderType())){
            enterStockDTO.getEnterStock().setRelatedOrder("");
            enterStockDTO.getNewCarDTOList().stream().forEach(newCarDetailDTO -> newCarDetailDTO.setOrderNo(finalOrderNo));
        }
        return FeignUtils.getHttpApi(KeyManagementApi.class).insertOrUpdateEnterStock(enterStockDTO);
    }

    @Override
    public Result invalidOrSubmit(String orderNo,Integer status) {
        //更新入库单状态
        return FeignUtils.getHttpApi(KeyManagementApi.class).invalidOrSubmit(orderNo,status);
    }
}
